using System;
using System.Collections.Specialized;
using System.IO;
using System.Web;
using System.Web.Caching;
using System.Xml.Serialization;
using newtelligence.DasBlog.Runtime;
using newtelligence.DasBlog.Util;

namespace newtelligence.DasBlog.Web.Core
{
	[XmlType(Namespace="urn:newtelligence-com:dasblog:config")]
	[XmlRoot(Namespace="urn:newtelligence-com:dasblog:config")]
	public class RobotDefinition
	{
		#region Fields
		private StringCollection _domains; 
		private StringCollection _userAgents;
		#endregion

		#region Properties
		public StringCollection Domains
		{
			get
			{
				return _domains;
			}
			set
			{
				_domains = value;
			}
		}

		public StringCollection UserAgents
		{
			get
			{
				return _userAgents;
			}
			set
			{
				_userAgents = value;
			}
		}
		#endregion

		#region Methods
		public bool IsRobot(LogDataItem logDataItem)
		{
			if (this.Domains.Contains(logDataItem.UserDomain.Trim()) ||
				this.UserAgents.Contains(logDataItem.UserAgent.Trim()))
			{
				return true;
			}

			return false;
		}
		#endregion

		#region Get Robots Definition
		public static RobotDefinition GetRobotDefinition()
		{
			RobotDefinition definition = (RobotDefinition) HttpContext.Current.Cache["RobotDefinition"];
			
			if (definition == null)
			{
				definition = GetRobotDefinition(GetConfigFilePathFromCurrentContext());
				HttpContext.Current.Cache.Insert("RobotDefinition", definition, new CacheDependency(HttpContext.Current.Server.MapPath("~/SiteConfig/robots.config")));
			}

			return definition;
		}

		public static RobotDefinition GetRobotDefinition(string configPath)
		{
			RobotDefinition definition;
			XmlSerializer ser = new XmlSerializer(typeof (RobotDefinition));

			using (StreamReader reader = new StreamReader(configPath))
			{
				XmlNamespaceUpgradeReader xnur = new XmlNamespaceUpgradeReader(reader, "", "urn:newtelligence-com:dasblog:config");
				definition = ser.Deserialize(xnur) as RobotDefinition;
			}

			return definition;
		}

		public static string GetConfigFilePathFromCurrentContext()
		{
			return HttpContext.Current.Server.MapPath("~/SiteConfig/robots.config");
		}
		#endregion
	}
}
